package com.example.demo;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.user.entity.UUser;
import com.example.demo.user.service.UUserService;
import com.example.demo.util.exception.MyBusinessException;
import com.example.demo.util.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


@RestController
public class TestController {
    @Autowired
    private UUserService uUserService;

    @GetMapping("/hello")
    public UUser test(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
        UUser user = uUserService.login("1","2");
        return user;
    }

    @PostMapping("/hello2")
    public Result<UUser> test( UUser user2) {
        UUser user = uUserService.login("1","2");
        return Result.ok(user);
    }

    @GetMapping("/add")
    public Result<?> add() {
        UUser user = new UUser();
        user.setName("2");
        user.setAvatar("2");
        user.setStatus("2");
        uUserService.save(user);
        return Result.ok(user);
    }

    @GetMapping("/select")
    public Result<IPage<UUser>> test3() {
        Page<UUser> page = new Page<>(2,1);
        return Result.ok(uUserService.getUserList(page)).code(100).message("测试");
    }

    @GetMapping("/exception")
    @Transactional
    public Result<?> testException(){
        UUser user = new UUser();
        user.setName("12");
        user.setAvatar("12");
        user.setStatus("12");
        uUserService.save(user);
        int i=1/0;//该语句会触发算数异常,进入全局异常处理类,所以不会执行下面的语句

        Result<Object> result=new Result<>();
        result.setCode(200);
        result.setMessage("success");
        result.setData("cc");
        return result;
    }
    /**
     * 自定义异常
     */
    @GetMapping("/myException")
    public Result testMyException(){
        throw new MyBusinessException(508,"自定义的异常");
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String a = passwordEncoder.encode("123456");
        System.out.println(a);
    }

}
